// pages/paySuccess/paySuccess.js
var app = getApp();
var util=require("../../utils/util");
var home=require("../../api/home");
var group=require("../../api/group");

Page({
  /* 页面的初始数据*/
  data: {
    width: wx.getSystemInfoSync().screenWidth,
    info: '',
    check_index: 0,
    price: 0,
    money: 0,
    type: 0,
    courseId: '',
    businessId: '',
    pref_list: [],
    latitude: 22.820794,
    longitude: 113.284565,
    userinfo: '',
    token: '',
    activity_id: '',
    payStep: '',
    show_share: true,
    share_img: '',
    canvas_show: false,
    hold: true,
    hide_canvas: true,
    canvasBg: 'https://ossdev0.jiabala.com/EF5k5cx73FhrJ'
  },
  /*生命周期函数--监听页面加载*/
  onLoad: function (options) {
    var that = this;
    var index = options.index;
    wx.setNavigationBarTitle({ title: index==1?'支付成功':'报名成功' });
    var info=wx.getStorageSync('cour_details'),userinfo=wx.getStorageSync('userinfo'),token=wx.getStorageSync('token');
    // type 1-详情 2-订单   payStep 1-单独购买 2-定金开团 3开团价开团 3-定金参团 4-开团价参团
    that.setData({check_index:index,type:options.type,info:info,userinfo:userinfo,token:token,activity_type:app.globalData.activity_type});
    // 订单支付金额（不是体验课）
    if(index==1){
      var price=util.toDecimal(options.price);
      that.setData({price:price,money:options.money,activity_id:options.aid,payStep:options.payStep,group_aid:options.group_aid})
      // wx.getStorage({
      //   key: 'city',
      //   success:function(res){
      //     that.setData({latitude: res.data.lat,longitude:res.data.lng})
      //     //
      //     that.send_pref_after(token);
      //   }
      // })
    }
    // 更新课程套餐购买数
    if(options.type==1){
      app.globalData.change_courMeal=true
    }
    // 拼团启动画布
    if(options.payStep&&options.payStep!=1){
      wx.showLoading({title: ''})
      //
      that.get_order_info(options.orderId)
    }
  },
  // 跳转
  nav_order:function(){
    var that=this,type=that.data.type,payStep=that.data.payStep,index=2;
    if(payStep&&payStep!=1){
      index=5;
    }
    if(type==1){
      app.globalData.change_courMeal=false
      wx.reLaunch({
        url: '../../mypage/myOrder/myOrder?type='+index,
      })
    }else{
      wx.navigateBack({
        delta: 1,
        fail:function(res){
          wx.switchTab({
            url: '../home/home',
          })
        }
      });
    }
  },
  back_to:function(){
    var that=this,type=that.data.type;
    wx.navigateBack({
      delta: 1,
      fail:function(res){
        wx.switchTab({
          url: '../home/home',
        })
      }
    });
  },
  // 礼品券
  nav_pref:function(){
    wx.redirectTo({
      url: '../../mypage/myPrefer/myPrefer',
    })
  },
  // 活动
  nav_activity:function(){
    var that=this;
    wx.redirectTo({
      url: '../activity/activity?id='+that.data.activity_id,
    })
  },
  // 分享
  onShareAppMessage:function(e){
    var that=this,info=that.data.info,payStep=that.data.payStep,group_id=that.data.group_id,name=that.data.userinfo.nickName,group_aid=that.data.group_aid,hide_canvas=that.data.hide_canvas;
    if(e.from=="button"){
      if(payStep!=1){
        // if(!hide_canvas){
          if(payStep==2){payStep=4}
          if(payStep==3){payStep=5}
          return{
            title: info.name,
            path: '/pages/payCourse/payCourse?id='+info.setMealId+'&lessonTime='+info.lessonTime+'&type='+payStep+'&group_id='+group_id+'&group_aid='+group_aid,
            imageUrl: info.img
          }
        // }else{
        //   return{
        //     title: info.name,
        //     path: '/pages/groupCourse/groupCourse?id='+info.group_aid+'&type=2',
        //     imageUrl: info.img
        //   }
        // }
      }else{
        return{
          title: info.name,
          path: '/pages/courseDetail/courseDetail?id='+info.id+'&type=2',
          imageUrl: info.img
        }
      }
    }else{
      return{
        title: name+'邀请您一起关注家巴啦',
        path: '/pages/home/home',
        imageUrl: 'https://ossdev0.jiabala.com/xaSpNcZEmBSRd'
      }
    }
  },
  // 查询订单信息(获取拼团号)
  get_order_info:function(orderId){
    var that=this;
    group.get_order_info({id:orderId}).then(res=>{
      if(res.data.code==200){
        var info=res.data.data;
        that.setData({group_id:info.groupFoundId})
        that.get_group_detail(info.groupFoundId)
      }
    })
  },
  // 单个团详情(获取拼团剩余人数)
  get_group_detail:function(groupId){
    var that=this,info=that.data.info;
    var params={
      "activityId": that.data.group_aid,
      "groupId": groupId,
      "isLeader": 0
    }
    group.get_group_detail(params).then(res=>{
      if(res.data.code==200){
        var group_info=res.data.data;
        if(group_info.groupFound){
          if(group_info.groupFound.surplusCount>0){
            info.surplusCount=group_info.groupFound.surplusCount;
            that.setData({info:info})
            //
            that.create_code(info);
          }else{
            wx.hideLoading({})
          }
        }else{
          wx.hideLoading({})
        }
      }
    })
  },
  // 生成码
  create_code:function(info){
    var that=this,group_aid=that.data.group_aid,userinfo=that.data.userinfo;
    if(!userinfo.avatar){userinfo.avatar="https://ossdev0.jiabala.com/eEa8TnEiby7re"}
    var str=group_aid+"I"+2;
    var params={
      "str": str,
      "pagesPath": "pages/groupCourse/groupCourse"
    }
    group.create_code(params).then(res=>{
      if(res.data.code==200){
        Promise.all(
          [
            util.downLoadImg(that.data.canvasBg),
            util.downLoadImg(userinfo.avatar),
            util.downLoadImg(info.img),
            util.downLoadImg(res.data.data)
          ]
        ).then(res=>{
          that.setData({img1:res[0].tempFilePath,img2:res[1].tempFilePath,img3:res[2].tempFilePath,img4:res[3].tempFilePath,canvas_show:true,hide_canvas:false})
          //
          that.draw_share();
        })
      }
    })
  },
  // 购买成功后送礼品券
  send_pref_after:function(token){
    var that=this,courseId=that.data.courseId,businessId=that.data.businessId,userinfo=that.data.userinfo;
    var params={
      "businessId": businessId,
      "couponWay": 2,
      "courseId": courseId,
      "currentPage": 1,
      "pageSize": 10,
      "lat": that.data.latitude,
      "lng": that.data.longitude,
      "createBy": userinfo.id
    }
    home.send_pref_after(params,token).then(res=>{
      if(res.data.code==200){
        var list=res.data.data.records;
        for(var i=0;i<list.length;i++){
          list[i].couponStartTime=util.formatTime_year(new Date(list[i].couponStartTime))
          list[i].couponEndTime=util.formatTime_month(new Date(list[i].couponEndTime))
        }
        that.setData({pref_list: list})
      }
    })
  },
  // 画布
  draw_share: function () {
    var that=this,info=that.data.info,userinfo=that.data.userinfo,bg=that.data.img1,avatar=that.data.img2,courImg=that.data.img3,ewm=that.data.img4;
    var ctx = wx.createCanvasContext('shareCanvas');
    var width = that.data.width, height = that.data.width*1.55,x = width / 375;
    var name_width=ctx.measureText(userinfo.nickName).width;
    // 开始绘制
    // 背景
    ctx.drawImage(bg,0,0,width,height);
    ctx.save();
    ctx.beginPath();
    // 头像
    ctx.arc(((width/2)+1),60*x,40*x,0,2*Math.PI,!1)
    ctx.clip()
    ctx.drawImage(avatar, ((width/2)+1-40*x), 20*x, 80*x, 80*x)
    ctx.restore()
    // 昵称
    that.roundRect(ctx,(width-name_width)/2-10,90*x,name_width+30,20*x,10*x)
    ctx.setFillStyle("#FF5079");
    ctx.font = 'normal bold 12px SemHei';
    ctx.fillText(userinfo.nickName, (width - name_width) / 2, 104 * x);
    // 课程图片
    that.roundImg(ctx,courImg,(width-286*x)/2,250*x,286*x,180*x,10*x)
    // 价格
    ctx.setFillStyle("#FF6A5D");
    ctx.font = 'normal bold 18px SemHei';
    ctx.fillText("￥", (width-286*x)/2, 480 * x);
    ctx.font = 'normal bold 24px SemHei';
    ctx.fillText(info.groupPrice, (width-286*x)/2+18*x, 480 * x);
    ctx.setFillStyle("#B4B4B4");
    ctx.font = 'normal normal 12px SemHei';
    ctx.fillText("￥ "+info.setMealPrice, (width-286*x)/2+5*x, 497 * x);
    // 删除线
    ctx.beginPath();
    ctx.setStrokeStyle('#B4B4B4')
    ctx.setLineWidth(1)
    ctx.moveTo((width-286*x)/2+3*x, 492*x)
    ctx.lineTo((width-286*x)/2+62*x, 492*x)
    ctx.closePath();
    ctx.stroke()
    // 名额
    var num_width=ctx.measureText(info.surplusCount+"个").width;
    ctx.setFillStyle("#333");
    ctx.font = 'normal normal 12px SemHei';
    ctx.fillText("该团仅剩", (width-286*x)/2+3*x, 525 * x);
    ctx.fillText("名额了", (width-286*x)/2+num_width+57.5*x, 525 * x);
    ctx.setFillStyle("#FF6A5D");
    ctx.font = 'normal bold 12px SemHei';
    ctx.fillText(info.surplusCount+"个", (width-286*x)/2+54*x, 525 * x);
    ctx.setFillStyle("#333");
    ctx.font = 'normal normal 12px SemHei';
    ctx.fillText("赶紧一起来拼团开课吧!", (width-286*x)/2+3*x, 545 * x);
    // 小程序码
    ctx.arc(282*x,504*x,44*x,0,2*Math.PI,!1)
    ctx.clip()
    ctx.drawImage(ewm, 238*x, 460*x, 88*x, 88*x)
    ctx.restore()
    // 
    ctx.draw(true, function () {
      setTimeout(function () {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: width,
          height: height,
          canvasId: 'shareCanvas',
          fileType: 'png',
          success: function (res) {
            // console.log(res);
            wx.hideLoading({})
            that.setData({share_img: res.tempFilePath,show_share:false,canvas_show:false})
          }
        }, that)
      }, 300);
    })
  },
  // 昵称背景
  roundRect:function(ctx, x, y, w, h, r) {
    // 开始绘制
    ctx.beginPath()
    // 左上角
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
    // border-top
    ctx.moveTo(x + r, y)
    ctx.lineTo(x + w - r, y)
    ctx.lineTo(x + w, y + r)
    // 右上角
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
    // border-right
    ctx.lineTo(x + w, y + h - r)
    ctx.lineTo(x + w - r, y + h)
    // 右下角
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
    // border-bottom
    ctx.lineTo(x + r, y + h)
    ctx.lineTo(x, y + h - r)
    // 左下角
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
    // border-left
    ctx.lineTo(x, y + r)
    ctx.lineTo(x + r, y)
    //
    ctx.setFillStyle("#fff")
    ctx.fill()
    ctx.closePath()
   },
  // 图片圆角
  roundImg(ctx, img, x, y, w, h, r) {
    //img为绘制图片的本地路径
    if (w < 2 * r) { r = w / 2; }
    if (h < 2 * r) { r = h / 2; }
    ctx.save()  //保存前面绘制的内容
    ctx.beginPath();
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
    ctx.moveTo(x + r, y);
    ctx.lineTo(x + w - r, y);
    ctx.lineTo(x + w, y + r);
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
    ctx.lineTo(x + w, y + h - r);
    ctx.lineTo(x + w - r, y + h);
    ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
    ctx.lineTo(x + r, y + h);
    ctx.lineTo(x, y + h - r);
    ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
    ctx.lineTo(x, y + r);
    ctx.lineTo(x + r, y);
    ctx.clip()  //裁剪上述区域
    ctx.drawImage(img,x,y,w,h,r)  //把图片加到上述裁剪后的区域
    ctx.restore() 
    ctx.closePath();
  },
  open_mask:function(){
    this.setData({show_share:false})
  },
  close_mask:function(){
    this.setData({show_share:true})
  },
  // 保存图片
  confirm_img:function(){
    var that=this,share_img=that.data.share_img,hold=that.data.hold;
    if(hold){
      that.setData({hold:false})
      wx.saveImageToPhotosAlbum({
        filePath: share_img,
        success(res) {
          util.page_show_toast("保存成功",1500)
          that.setData({hold:true})
        },
        fail: function(){
          that.setData({hold:true})
        }
      })
    }
  },
})